import { computed, Ref, ref, watch, watchEffect } from "vue";

export function useDomRect(refDom: Ref<Element>): { rect: Ref<Partial<DOMRect>> } {
  const rect: Ref<Partial<DOMRect>> = ref({});
  let resizeObserver: ResizeObserver | null;
  watchEffect(() => {
    if (refDom.value) {
      console.log("ResizeObserver init");
      rect.value = refDom.value.getBoundingClientRect();
      if (resizeObserver) {
        // 大小位置 contentRect
        resizeObserver.disconnect();
      }
      resizeObserver = new ResizeObserver((entries) => {
        for (let entry of entries) {
          rect.value = entry.contentRect;
        }
      });
      resizeObserver.observe(refDom.value);
    } else {
      console.log("ResizeObserver release");
      if (resizeObserver) {
        resizeObserver.disconnect();
        resizeObserver = null;
      }
    }
  });
  return { rect };
}
